<template>
  <custom-dialog
    ref="dialog" :title="modalTitle" height="450px"
    :before-confirm="beforeConfirm" :on-confirm="onConfirm"
  >
    <el-form ref="form" :model="info" :rules="rules" label-width="120px">
      <el-form-item label="文件名称" prop="name">
        <el-input v-model="info.name"></el-input>
      </el-form-item>
      <el-form-item label="文件类型" prop="type">
        <dictionary-picker filterable clearable dic-code="WEN_JIAN_LEI_XING" v-model="info.type"></dictionary-picker>
      </el-form-item>
      <el-form-item label="上传文件" prop="url">
        <el-upload
          ref="uploader" class="upload-files" action="#"
          :limit="1" :on-change="onChange" :on-remove="onRemove"
          :auto-upload="false" :file-list="fileList"
        >
          <el-button :disabled="!!info.url" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
  </custom-dialog>
</template>

<script>
import CustomDialog from '@/components/custom-dialog'
import DictionaryPicker from '@/components/dictionary-picker'
import { saveOrUpdate } from '@/api/fileManagement'
import { upload } from '@/api/minio'

export default {
  name: 'operate-modal',
  components: { CustomDialog, DictionaryPicker },
  props: {
    modalTitle: String,
    modalData: {
      type: Object,
      default () {
        return {}
      }
    },
  },
  data () {
    return {
      fileList: [],
      info: {
        id: '',
        name: '',
        url: '',
        type: '',
      },
      rules: {
        name: [{ required: true, message: '必填项' }],
        type: [{ required: true, message: '必填项' }],
        url: [{ required: true, message: '必填项', trigger: 'change' }],
      },
    }
  },
  methods: {
    open () {
      this.info = {
        ...this.$options.data().info,
        ...this.modalData,
      }
      const isAdd = Object.keys(this.modalData).length === 0
      if (isAdd) {
        this.fileList = []
      } else {
        this.fileList = [{
          name: this.info.name,
          url: this.info.url,
        }]
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.$nextTick(() => {
        this.$refs.dialog.open()
      })
    },
    beforeConfirm () {
      return this.$refs.form.validate()
    },
    onConfirm (close) {
      const rawFile = this.info.url
      return upload(rawFile).then((res) => {
        if (res.code === 200) {
          const params = { ...this.info }
          params.url = res.data.url

          return saveOrUpdate(params).then(res => {
            if (res.code === 200) {
              this.$emit('save-success')
              this.$message.success('保存成功')
              close()
            }
          })
        }
      })
    },
    onRemove () {
      this.info.url = ''
      this.fileList = []
      this.$refs.form.validateField('url')
    },
    onChange (file) {
      this.info.url = file.raw
      this.$refs.form.validateField('url')
    },
  },
}
</script>
